import 'package:flutter/material.dart';

class InfinitePageViewDemo extends StatefulWidget {
  @override
  _InfinitePageViewDemoState createState() => _InfinitePageViewDemoState();
}

class _InfinitePageViewDemoState extends State<InfinitePageViewDemo> {
  late PageController _pageController;
  List<String> _items = [];
  int _currentIndex = 1000000; // 从中间开始，模拟无限循环
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    // 初始化数据
    _loadInitialData();
    _pageController = PageController(initialPage: _currentIndex);
  }

  void _loadInitialData() {
    // 模拟初始数据加载
    for (int i = 0; i < 20; i++) {
      _items.add('初始数据 $i');
    }
  }

  // 模拟加载更多数据
  Future<void> _loadMoreData(bool isNext) async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
    });

    // 模拟网络请求延迟
    await Future.delayed(Duration(seconds: 1));

    setState(() {
      if (isNext) {
        // 加载下一页数据
        for (int i = 0; i < 5; i++) {
          _items.add('新数据 ${_items.length + i}');
        }
      } else {
        // 加载上一页数据（在列表前面插入）
        for (int i = 0; i < 5; i++) {
          _items.insert(0, '历史数据 ${_items.length - i}');
        }
        // 调整当前索引以保持视觉位置不变
        _currentIndex += 5;
      }
      _isLoading = false;
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('无限加载 PageView'),
        backgroundColor: Colors.blue,
        actions: [
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: () {
              setState(() {
                _items.clear();
                _loadInitialData();
                _currentIndex = 1000000;
                _pageController.jumpToPage(_currentIndex);
              });
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 页面信息显示
          Container(
            padding: EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('当前页: ${_currentIndex}'),
                Text('总页数: ${_items.length}'),
                _isLoading
                  ? SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : Icon(Icons.check, color: Colors.green, size: 20),
              ],
            ),
          ),

          // 无限 PageView
          Expanded(
            child: PageView.builder(
              controller: _pageController,
              onPageChanged: (int index) {
                setState(() {
                  _currentIndex = index;
                });

                // 预加载逻辑
                if (index > _items.length - 3) {
                  // 接近末尾时加载更多
                  _loadMoreData(true);
                } else if (index < 3 && _items.length > 10) {
                  // 接近开头时加载历史数据
                  _loadMoreData(false);
                }
              },
              itemBuilder: (context, index) {
                // 处理边界情况
                if (index < 0 || _items.isEmpty) {
                  return _buildLoadingPage('加载中...');
                }

                // 循环显示内容
                int actualIndex = index % _items.length;
                if (actualIndex < 0) {
                  actualIndex += _items.length;
                }

                return _buildContentPage(index, actualIndex);
              },
            ),
          ),

          // 控制按钮
          Container(
            padding: EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () {
                    if (_currentIndex > 0) {
                      _pageController.previousPage(
                        duration: Duration(milliseconds: 300),
                        curve: Curves.easeInOut,
                      );
                    }
                  },
                  child: Text('上一页'),
                ),
                ElevatedButton(
                  onPressed: () {
                    _pageController.nextPage(
                      duration: Duration(milliseconds: 300),
                      curve: Curves.easeInOut,
                    );
                  },
                  child: Text('下一页'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLoadingPage(String text) {
    return Container(
      color: Colors.grey[200],
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 20),
            Text(text),
          ],
        ),
      ),
    );
  }

  Widget _buildContentPage(int pageIndex, int actualIndex) {
    Color color = Colors.primaries[actualIndex % Colors.primaries.length];

    return Container(
      color: color.withOpacity(0.1),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.pages,
            size: 80,
            color: color,
          ),
          SizedBox(height: 20),
          Text(
            '页面索引: $pageIndex',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 10),
          Text(
            '实际内容: ${_items[actualIndex]}',
            style: TextStyle(fontSize: 16),
          ),
          SizedBox(height: 10),
          Text(
            '数据索引: $actualIndex',
            style: TextStyle(fontSize: 14, color: Colors.grey[600]),
          ),
          if (_isLoading)
            Padding(
              padding: EdgeInsets.all(16),
              child: Text('正在加载更多数据...', style: TextStyle(color: Colors.blue)),
            ),
        ],
      ),
    );
  }
}

// 真正的无限循环 PageView（首尾相连）
class TrueInfinitePageViewDemo extends StatefulWidget {
  @override
  _TrueInfinitePageViewDemoState createState() => _TrueInfinitePageViewDemoState();
}

class _TrueInfinitePageViewDemoState extends State<TrueInfinitePageViewDemo> {
  late PageController _pageController;
  List<String> _items = [];
  int _fakeIndex = 500; // 虚拟索引，用于模拟无限循环
  static const int _bufferSize = 1000; // 缓冲区大小

  @override
  void initState() {
    super.initState();
    _loadInitialData();
    _pageController = PageController(initialPage: _fakeIndex);
  }

  void _loadInitialData() {
    // 初始化固定数据集
    for (int i = 1; i <= 10; i++) {
      _items.add('内容项目 $i');
    }
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('真正无限循环 PageView'),
        backgroundColor: Colors.green,
      ),
      body: Column(
        children: [
          // 信息显示
          Container(
            padding: EdgeInsets.all(16),
            child: Text(
              '虚拟索引: $_fakeIndex, 实际项目: ${_fakeIndex % _items.length}',
              style: TextStyle(fontSize: 16),
            ),
          ),

          // 真正的无限循环 PageView
          Expanded(
            child: PageView.builder(
              controller: _pageController,
              onPageChanged: (int index) {
                setState(() {
                  _fakeIndex = index;
                });
              },
              itemBuilder: (context, index) {
                // 使用模运算实现无限循环
                int actualIndex = index % _items.length;
                if (actualIndex < 0) {
                  actualIndex += _items.length;
                }

                Color color = Colors.primaries[actualIndex % Colors.primaries.length];

                return Container(
                  color: color.withOpacity(0.2),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.loop,
                        size: 80,
                        color: color,
                      ),
                      SizedBox(height: 20),
                      Text(
                        '无限循环页面',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 10),
                      Text(
                        '虚拟索引: $index',
                        style: TextStyle(fontSize: 16),
                      ),
                      SizedBox(height: 10),
                      Text(
                        '实际内容: ${_items[actualIndex]}',
                        style: TextStyle(fontSize: 18, color: color),
                      ),
                      SizedBox(height: 10),
                      Text(
                        '实际索引: $actualIndex',
                        style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                      ),
                    ],
                  ),
                );
              },
            ),
          ),

          // 控制按钮
          Container(
            padding: EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () {
                    _pageController.previousPage(
                      duration: Duration(milliseconds: 300),
                      curve: Curves.easeInOut,
                    );
                  },
                  child: Text('上一页'),
                ),
                ElevatedButton(
                  onPressed: () {
                    _pageController.nextPage(
                      duration: Duration(milliseconds: 300),
                      curve: Curves.easeInOut,
                    );
                  },
                  child: Text('下一页'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// 带预加载和缓存的无限 PageView
class AdvancedInfinitePageViewDemo extends StatefulWidget {
  @override
  _AdvancedInfinitePageViewDemoState createState() => _AdvancedInfinitePageViewDemoState();
}

class _AdvancedInfinitePageViewDemoState extends State<AdvancedInfinitePageViewDemo> {
  late PageController _pageController;
  Map<int, String> _pageCache = {}; // 页面缓存
  int _currentIndex = 0;
  int _maxLoadedIndex = 0;
  int _minLoadedIndex = 0;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _preloadPages(0);
    _pageController = PageController(initialPage: _currentIndex);
  }

  // 预加载页面数据
  void _preloadPages(int centerIndex) {
    setState(() {
      _isLoading = true;
    });

    // 预加载前后5页的数据
    for (int i = centerIndex - 5; i <= centerIndex + 5; i++) {
      if (!_pageCache.containsKey(i)) {
        _pageCache[i] = '页面内容 $i - 预加载于 ${DateTime.now().second}秒';
      }
    }

    setState(() {
      _maxLoadedIndex = _pageCache.keys.fold(_maxLoadedIndex, (a, b) => a > b ? a : b);
      _minLoadedIndex = _pageCache.keys.fold(_minLoadedIndex, (a, b) => a < b ? a : b);
      _isLoading = false;
    });
  }

  // 模拟从网络获取数据
  Future<String> _fetchPageData(int index) async {
    await Future.delayed(Duration(milliseconds: 200 + (index % 3) * 100));
    return '网络数据 - 页面 $index\n加载时间: ${DateTime.now().toIso8601String()}';
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('高级无限 PageView'),
        backgroundColor: Colors.purple,
        actions: [
          IconButton(
            icon: Icon(Icons.clear_all),
            onPressed: () {
              setState(() {
                _pageCache.clear();
                _currentIndex = 0;
                _maxLoadedIndex = 0;
                _minLoadedIndex = 0;
                _pageController.jumpToPage(0);
                _preloadPages(0);
              });
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 状态信息
          Container(
            padding: EdgeInsets.all(16),
            child: Column(
              children: [
                Text('当前页: $_currentIndex'),
                Text('缓存页数: ${_pageCache.length}'),
                Text('缓存范围: $_minLoadedIndex ~ $_maxLoadedIndex'),
                if (_isLoading)
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      ),
                      SizedBox(width: 10),
                      Text('正在预加载...'),
                    ],
                  ),
              ],
            ),
          ),

          // 高级无限 PageView
          Expanded(
            child: PageView.builder(
              controller: _pageController,
              onPageChanged: (int index) {
                setState(() {
                  _currentIndex = index;
                });

                // 智能预加载
                _preloadPages(index);
              },
              itemBuilder: (context, index) {
                return _buildPage(index);
              },
            ),
          ),

          // 控制和信息按钮
          Container(
            padding: EdgeInsets.all(16),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                      onPressed: _currentIndex > 0
                          ? () {
                              _pageController.previousPage(
                                duration: Duration(milliseconds: 300),
                                curve: Curves.easeInOut,
                              );
                            }
                          : null,
                      child: Text('上一页'),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        _pageController.nextPage(
                          duration: Duration(milliseconds: 300),
                          curve: Curves.easeInOut,
                        );
                      },
                      child: Text('下一页'),
                    ),
                  ],
                ),
                SizedBox(height: 10),
                ElevatedButton(
                  onPressed: () async {
                    String data = await _fetchPageData(_currentIndex);
                    setState(() {
                      _pageCache[_currentIndex] = data;
                    });
                  },
                  child: Text('强制刷新当前页'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPage(int index) {
    Color color = Colors.primaries[index.abs() % Colors.primaries.length];

    return Container(
      color: color.withOpacity(0.1),
      child: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.cloud_download,
              size: 80,
              color: color,
            ),
            SizedBox(height: 20),
            Text(
              '页面索引: $index',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: 20),

            // 显示缓存的数据
            Container(
              padding: EdgeInsets.all(16),
              margin: EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.3),
                    spreadRadius: 1,
                    blurRadius: 5,
                    offset: Offset(0, 3),
                  ),
                ],
              ),
              child: Column(
                children: [
                  Text(
                    '页面内容:',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 10),
                  Text(
                    _pageCache.containsKey(index)
                        ? _pageCache[index]!
                        : '数据加载中...',
                    style: TextStyle(fontSize: 16),
                    textAlign: TextAlign.center,
                  ),
                  if (!_pageCache.containsKey(index))
                    Padding(
                      padding: EdgeInsets.all(8),
                      child: CircularProgressIndicator(),
                    ),
                ],
              ),
            ),

            // 缓存状态
            Container(
              padding: EdgeInsets.all(16),
              child: Text(
                _pageCache.containsKey(index)
                    ? '✓ 数据已缓存'
                    : '⚠ 数据未缓存',
                style: TextStyle(
                  fontSize: 16,
                  color: _pageCache.containsKey(index) ? Colors.green : Colors.orange,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 主页面 - 展示所有无限 PageView 示例
class InfinitePageViewMainDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('无限 PageView 示例'),
        backgroundColor: Colors.blue,
      ),
      body: ListView(
        padding: EdgeInsets.all(16),
        children: [
          _buildDemoCard(
            context,
            '基础无限加载',
            '支持向前向后无限加载数据',
            Icons.autorenew,
            () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => InfinitePageViewDemo()),
            ),
          ),
          _buildDemoCard(
            context,
            '真正无限循环',
            '首尾相连的无限循环页面',
            Icons.loop,
            () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => TrueInfinitePageViewDemo()),
            ),
          ),
          _buildDemoCard(
            context,
            '高级无限 PageView',
            '带缓存和预加载功能',
            Icons.flash_auto,
            () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => AdvancedInfinitePageViewDemo()),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDemoCard(BuildContext context, String title, String description,
      IconData icon, VoidCallback onTap) {
    return Card(
      margin: EdgeInsets.symmetric(vertical: 8),
      elevation: 4,
      child: ListTile(
        leading: Icon(icon, size: 40, color: Colors.blue),
        title: Text(
          title,
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        subtitle: Text(description),
        trailing: Icon(Icons.arrow_forward_ios),
        onTap: onTap,
      ),
    );
  }
}

// 使用示例
void main() {
  runApp(MaterialApp(
    title: '无限 PageView Demo',
    debugShowCheckedModeBanner: false,
    home: InfinitePageViewMainDemo(),
  ));
}
